#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :pantum_login.py
# Time  :2025/5/20 14:31
# Email :fortunatedong@163.com
# Author:by Adonli
import asyncio
from playwright.async_api import async_playwright
import json
import time
import os

from config import ROOT_DIR

pantum_cookie_json = os.path.join(ROOT_DIR, 'utils/monitoring_early_warning/auth', 'pantum_cookie.json')

async def login_with_retry(page, max_retries=3, retry_delay=3):
    """
    带重试机制的登录函数
    :param page: Playwright 页面对象
    :param max_retries: 最大重试次数
    :param retry_delay: 重试间隔(秒)
    :return: 登录成功返回True，失败返回False
    """
    for attempt in range(max_retries):
        try:
            # 这里替换为实际的登录操作
            # 示例：登录一个假设的网站
            await page.goto('https://css.pantum.com/admin/login.jsp')
            # 等待iframe加载完成（替换为实际的iframe选择器）
            frame = await page.wait_for_selector('//iframe[@id="customPage"]')
            # 获取iframe的内容框架
            frame_content = await frame.content_frame()
            # 填写用户名和密码（替换为实际的元素选择器）
            await frame_content.fill('//input[@id="username"]', 'xxxxxxxxxx')
            time.sleep(1)
            await frame_content.fill('//input[@id="password"]', 'xxxxxxxxxxxx')
            time.sleep(1)
            await frame_content.locator('//input[@type="checkbox"]').click()
            time.sleep(1)
            # 点击登录按钮
            await frame_content.click('//input[@value="登录"]')

            # 等待登录成功后的页面元素出现（替换为实际的元素选择器）
            await page.wait_for_selector('//li[@class="message"]', timeout=5000)

            print("登录成功！")
            return True

        except Exception as e:
            print(f"登录尝试 {attempt + 1}/{max_retries} 失败: {str(e)}")
            if attempt < max_retries - 1:
                print(f"{retry_delay}秒后重试...")
                time.sleep(retry_delay)
            else:
                print("达到最大重试次数，登录失败")
                return False


async def get_cookies(page):
    """
    获取当前页面的cookies
    :param page: Playwright 页面对象
    :return: cookies列表
    """
    return await page.context.cookies()


async def save_cookies(cookies):
    """
    保存cookies到文件
    :param cookies: cookies列表
    :param filename: 保存文件名
    """
    with open(pantum_cookie_json, 'w') as f:
        json.dump(cookies, f, indent=2)
    print(f"Cookies已保存到 {pantum_cookie_json}")


async def main():
    async with async_playwright() as p:
        # 启动浏览器（可以改为 p.firefox 或 p.webkit）
        browser = await p.chromium.launch(headless=True,channel="chrome")  # 调试时可设置为False查看浏览器

        # 创建新上下文和页面
        context = await browser.new_context()
        page = await context.new_page()

        try:
            # 尝试登录
            login_success = await login_with_retry(page)

            if login_success:
                # 获取并保存cookies
                cookies = await get_cookies(page)
                await save_cookies(cookies)

                # 这里可以继续其他操作...
                # 例如访问需要登录的页面
                # await page.goto('https://example.com/protected-page')

            else:
                print("登录失败，无法继续操作")

        except Exception as e:
            print(f"发生错误: {str(e)}")
        finally:
            # 关闭浏览器
            await browser.close()


if __name__ == '__main__':
    asyncio.run(main())